package com.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author 罗俊华
 * @date 2021/8/24 - 5:17 下午
 */
@Slf4j
public class AsyncIo {


    public static void main(String[] args) {

//        ExecutorService executorService = Executors.newCachedThreadPool();
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/Users/luo/temp/netty_learning/basic/words.txt"), StandardOpenOption.READ)) {

            ByteBuffer byteBuffer = ByteBuffer.allocate(16);

            fileChannel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("文件读取完成");
                    attachment.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(attachment));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });

            log.debug("nio异步读取任务已创建");

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}
